import os


def clear_remote_dir(sftp, remote_dir):
    print('正在删除远程目录')
    try:
        files = sftp.listdir(remote_dir)
        for file in files:
            file_path = os.path.join(remote_dir, file)
            try:
                sftp.remove(file_path)
            except IOError:
                clear_remote_dir(sftp, file_path)
                sftp.rmdir(file_path)
    except FileNotFoundError:
        sftp.mkdir(remote_dir)


def upload_dir(sftp, local_dir, remote_dir):
    # 清空远程目录中的所有文件和子目录
    clear_remote_dir(sftp, remote_dir)
    print('正在上传文件到服务器...')
    for item in os.listdir(local_dir):
        local_path = os.path.join(local_dir, item)
        remote_path = os.path.join(remote_dir, item)

        if os.path.isdir(local_path):
            upload_dir(sftp, local_path, remote_path)
        else:
            sftp.put(local_path, remote_path)
